package com.dgut.courses_selecting_sys.controller;


import com.dgut.courses_selecting_sys.entity.AjaxResult;
import com.dgut.courses_selecting_sys.entity.Dept;
import com.dgut.courses_selecting_sys.entity.User;
import com.dgut.courses_selecting_sys.enums.ExportEnum;
import com.dgut.courses_selecting_sys.service.IDeptService;
import com.dgut.courses_selecting_sys.service.IUserRoleService;
import com.dgut.courses_selecting_sys.service.IUserService;
import com.dgut.courses_selecting_sys.utils.ExcelUtils;
import com.dgut.courses_selecting_sys.utils.ShiroUtils;
import com.dgut.courses_selecting_sys.utils.core.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yuec
 * @since 2020-07-23
 */
@Slf4j
@Controller
@RequestMapping("//user")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    IUserRoleService userRoleService;

    @Autowired
    IDeptService deptService;

    /**
     * 更新用户数据
     *
     * @param user
     * @return
     */
    @ResponseBody
    @PostMapping("/alter")
    public AjaxResult alterUser(User user) {
        user.setUserId(ShiroUtils.getSysUser().getUserId());
        user.setLoginName(ShiroUtils.getSysUser().getLoginName());
        user.setDeptId(ShiroUtils.getSysUser().getDeptId());
        if (userService.updateUser(user) != null) {
            ShiroUtils.clearCachedAuthorizationInfo();
            return AjaxResult.success();
        } else {
            return AjaxResult.error("用户数据更新失败");
        }
    }


    @RequiresRoles("admin")
    @GetMapping("/teachManage")
    public String teachManage() {
        return "admin/teachManage";
    }

    @RequiresRoles("admin")
    @GetMapping("/stuManage")
    public String stuManage() {
        return "admin/stuManage";
    }

    /**
     * 查找dept节点的教师
     *
     * @param deptId
     * @return
     */
    @RequiresRoles("admin")
    @ResponseBody
    @PostMapping("teachers/list")
    public AjaxResult teachList(int deptId) {

        List<User> list = userRoleService.teachList(deptId);
        if (list.size() == 0) {
            return AjaxResult.error("没查询到数据！");
        }
        return AjaxResult.success("查询成功!", list);
    }

    /**
     * 查找dept下的学生
     *
     * @param deptId
     * @return
     */
    @ResponseBody
    @PostMapping("student/list")
    public AjaxResult studentList(int deptId) {

        List<User> list = userRoleService.stuList(deptId);
        if (list.size() == 0) {
            return AjaxResult.error("没查询到数据！");
        }
        return AjaxResult.success("查询成功!", list);
    }

    /**
     * 恢复停用的账户
     *
     * @param userId
     * @return
     */
    @RequiresRoles("admin")
    @ResponseBody
    @PostMapping("/recoverUser")
    public AjaxResult recoverUser(Long userId) {
        if (userService.recoverUser(userId)) {
            return AjaxResult.success("账户已恢复");
        } else {
            return AjaxResult.error("账户恢复出现错误！！！！");
        }

    }

    /**
     * 停用指定的账户
     *
     * @param userId
     * @return
     */
    @RequiresRoles("admin")
    @ResponseBody
    @PostMapping("/disableUser")
    public AjaxResult disableUser(Long userId) {
        if (userService.disableUser(userId)) {
            return AjaxResult.success("账户已停用");
        } else {
            return AjaxResult.error("账户停用出现错误！！！！");
        }
    }

    /**
     * 重置密码
     *
     * @param userId
     * @param password
     * @return
     */
    @RequiresRoles("admin")
    @ResponseBody
    @PostMapping("/resetPassword")
    public AjaxResult resetPassword(Long userId, String password) {
        if (userService.resetPassword(userId, password)) {
            return AjaxResult.success("密码重置成功，初始密码为“123456");
        } else {
            return AjaxResult.error("重置密码出错");
        }
    }

    /**
     * 导出账户
     *
     * @param deptId
     * @param response
     * @throws Exception
     */
    @PostMapping("/exportByDeptId")
    public void exportByDeptId(@RequestParam("deptId") int deptId, HttpServletResponse response) {
        response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        Map map = new HashMap();
        map.put("dept_id", deptId);
        List<User> list = userService.listByMap(map);
        for (User user : list) {
            if (user.getStatus().equals("0")) {
                user.setStatus("正常");
            } else if (user.getStatus().equals("1")) {
                user.setStatus("停用");
            } else {
                user.setStatus("删除");
            }

            if (StringUtils.isNotNull(user.getSex()) && user.getSex().equals("0")) {
                user.setSex("女");
            } else {
                user.setSex("男");
            }
        }
        try {
            if (deptService.getByDeptId(deptId).getAncestors().split(",").length>2){
                ExcelUtils.writeExcel(response, list, User.class, ExportEnum.STUDENT);
            }
            ExcelUtils.writeExcel(response, list, User.class, ExportEnum.TEACHER);
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    /**
     *
     */
    @PostMapping("/inputUserTemplate")
    public void inputUserTemplate(HttpServletResponse response) {
        response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            ClassPathResource classPathResource = new ClassPathResource("static/xlsx/abc.xlsx");
            File file = classPathResource.getFile();
            InputStream inputStream = classPathResource.getInputStream();
            InputStream fis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();

            //获取文件的名字再浏览器下载页面
            String name = file.getName();
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("导入模板.xlsx", "utf-8"));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream out = new BufferedOutputStream(response.getOutputStream());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            out.write(buffer);
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    /**
     * 导入excel文件，创建多个账户
     *
     * @param deptId
     * @param file
     * @return
     */
    @RequiresRoles("admin")
    @ResponseBody
    @PostMapping("/createUser")
//    @CacheEvict(value = {"ListStuByDeptId","ListTeachByDeptId"}, key = "#deptId")
    public AjaxResult createUser(@RequestParam("deptId") int deptId, MultipartFile file) {
        try {
            List<User> list = ExcelUtils.readExcel("", User.class, file);
            Map<String, String> map = new HashMap<>();
            Dept dept = deptService.getByDeptId(deptId);
            int roleId ;
            if ((dept.getAncestors().length() - dept.getAncestors().replaceAll(",", "").length()) == 1) {
                roleId = 2;
            } else {
                roleId = 3;
            }
            for (User user : list) {
                user.setDeptId(deptId);
                if (userService.createUser(user, roleId) != null) {
                    map.put("\n" + user.getLoginName(), user.getUserName());
                }
            }
            if (map.size() == 0) {
                return AjaxResult.success("全部添加成功");
            } else {
                System.out.println(map);
                return AjaxResult.success("以下成员添加不成功！", map.toString());
            }
        } catch (Exception e) {
            return AjaxResult.error("系统解析文件时发生错误！！！");
        }

    }


}

